//
//  FPLoanController.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/1/23.
//

#import "FPLoanController.h"
#import "FPLoanController.h"
#import "FPLoanHeaderView.h"
#import "FPPeriodMainView.h"
#import "FPRepayPlanMainView.h"
#import "FPRepayPlanModel.h"
#import "FPBankCardModel.h"
#import "FPBankCardInfoMainView.h"
#import "FPAddNewBankCardController.h"
#import "FPAuthenticationFooterView.h"
#import "FPLoanModel.h"
#import "FPInreviewController.h"
#import "FPConfirmLoanContractController.h"
#import "FPLoanDetailModel.h"
#import "FPRecommonProductController.h"

@interface FPLoanController () <UITableViewDelegate , UITableViewDataSource , HJCActionSheetDelegate , TTTAttributedLabelDelegate , UITextFieldDelegate , UIGestureRecognizerDelegate>

@property (nonatomic , strong) FPAuthenticationFooterView *footerView; //!< 确认& 协议

@property (nonatomic , strong) FPLoanHeaderView *headerView;
@property (nonatomic , strong) FPPeriodMainView *headerPeriodMainView;
@property (nonatomic , strong) FPRepayPlanMainView *headerRepayPlanMainView;
@property (nonatomic , strong) FPBankCardInfoMainView *bankCardInfoMainView;

@property (nonatomic , assign) BOOL isSelect;

@property (nonatomic , assign) NSInteger termIndex; //!< 借多久 默认:3 即12个月
@property (nonatomic , strong) NSString *termString; //!< 借多久 默认:3 即12个月

@property (nonatomic , strong) NSArray *usageArray;
@property (nonatomic , assign) NSInteger usageIndex; //!< 日常消费

@property (nonatomic , strong) NSMutableArray *bankCardSource;
@property (nonatomic , assign) NSInteger bankCardSelectIndex;
@property (nonatomic , strong) NSMutableArray *repaymentSource;

@property (nonatomic , strong) NSString *rate; //!< 利率 debug: 24 这个要从首页去拿
@property (nonatomic , strong) NSString *bankImgInfo;
@property (nonatomic , strong) NSString *bankCardInfo;
@property (nonatomic , strong) NSMutableArray *protocolSource;

@property (nonatomic , strong) NSString *dateFromService; //!< 服务器时间
@property (nonatomic , strong) NSString *bankCardUserName; //!< 银行卡持有人名
@property (nonatomic , strong) NSString *affiliation; //!< 银行卡开户行
@property (nonatomic , strong) NSString *bankCardNumber; //!< 银行卡号

@property (nonatomic , strong) NSString *keyContractWithTimestamp; //!< 带时间戳的标识, 传给H5 生成合同

@property (nonatomic , assign) NSInteger index;

@end
 
@implementation FPLoanController

LazyLoadDataSource(bankCardSource);
LazyLoadDataSource(repaymentSource);
LazyLoadDataSource(protocolSource);

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    // 只有当前控制器在导航栈顶才设置手势代理
    if (self.navigationController.viewControllers.lastObject == self) {
        self.navigationController.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>)self;
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    // 离开页面前恢复手势代理（防止影响其他页面）
    if (self.navigationController.interactivePopGestureRecognizer.delegate == (id<UIGestureRecognizerDelegate>)self) {
        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }
}


- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    
    [self detainmentPopupAction];
    
    return NO;
}

- (void)backAction {
    
    [self detainmentPopupAction];
}

- (void)detainmentPopupAction {
    
    LXAlertView *alert = [[LXAlertView alloc] initDetainmentWithTitleString:@"借款未完成，确认退出吗" contentString:@"您的额度超过了93%的人，借款后最快3分钟即可到账" btn1:@"去意已决" btn2:@"继续申请借款" alertAlertResult:^(NSInteger index) {
        
        if (index == 2) {
            
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
    [alert showLXAlertView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.index = 0;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    // 删除控制器
    NSMutableArray *marr = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers];
    
    for (UIViewController *vc in marr) {
    
        if ([vc isKindOfClass:NSClassFromString(@"FPMeProfileController")]) {
            
            [marr removeObject:vc];
            break;
        }
    }
    
    for (UIViewController *vc in marr) {
    
        if ([vc isKindOfClass:NSClassFromString(@"FPMeProfileTwoController")]) {
            
            [marr removeObject:vc];
            break;
        }
    }
    
    for (UIViewController *vc in marr) {
    
        if ([vc isKindOfClass:NSClassFromString(@"FPExcessiveController")]) {
            
            [marr removeObject:vc];
            break;
        }
    }
    
    self.navigationController.viewControllers = marr;
}

- (void)initUI {
    
    self.rate = @"24";
    
    self.bankCardSelectIndex = -1;
    
    self.termIndex = 3;
    self.termString = @"12期";
    
    self.usageArray = @[@"日常消费", @"装修", @"教育", @"手机数码", @"电器", @"其他"];
    self.usageIndex = 0;
    
    self.isSelect = NO;
    
    [self setTitle:@"借款" style:(XYCustomNavigationStyleWhite) hiddenBackBtn:NO];
    
    self.view.backgroundColor = MAIN_VIEW_BACKGROUND_COLOR;
    
    self.footerView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPAuthenticationFooterView.class) owner:nil options:nil].lastObject;
    [self.view addSubview:self.footerView];
    self.footerView.frame = CGRectMake(0.f, SCREEN_HEIGHT - 130.f - UIDevice.safeDistanceBottom, SCREEN_WIDTH, 130.f);
    self.footerView.backgroundColor = UIColor.whiteColor;
    [self.footerView setShadow];
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0.f, SCREEN_HEIGHT - UIDevice.safeDistanceBottom, SCREEN_WIDTH, UIDevice.safeDistanceBottom)];
    v.backgroundColor = MAIN_VIEW_BACKGROUND_COLOR;
    [self.view addSubview:v];
    
    [self.footerView.nextBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
            
//        [self showText:@"借款~"];
        [self submitAction];
    }];
    
    [self getProtocol];
    [self getServiceDate];
    
    [self.footerView.nextBtn setTitle:@"下一步" forState:(UIControlStateNormal)]; // 确认借款
    [self.footerView.selectImgView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectAction)]];
    [self.footerView.imgBackView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectAction)]];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.tableView.frame = CGRectMake(0.f, UIDevice.navigationFullHeight, SCREEN_WIDTH, SCREEN_HEIGHT - UIDevice.navigationFullHeight - UIDevice.safeDistanceBottom - 130.f);
    self.tableView.backgroundColor = MAIN_VIEW_BACKGROUND_COLOR;
    
    self.tableView.rowHeight = 2.f;
    
    self.headerView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPLoanHeaderView.class) owner:nil options:nil].lastObject;
    self.tableView.tableHeaderView = self.headerView;
    self.headerView.amountTF.delegate = self;
    
    self.headerView.tipTitleLa.hidden = YES;
    self.headerView.tipContentLab.hidden = YES;
    
    self.headerView.purposeLab.text = self.usageArray[self.usageIndex];
    
    [self.headerView.periodView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(periodSelectAction)]];
    [self.headerView.repayPlanView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(repaySelectAction)]];
    [self.headerView.bankInfoView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bankInfoSelectAction)]];
    [self.headerView.purposeView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(purposeSelectAction)]];
    
    // 借款利率
//    self.headerView.tipLab8.text = [NSString stringWithFormat:@"%@%%", self.rate] ;
    
//    CGFloat height = [UIView heightWithString:self.headerView.tipContentLab.text labelWidth:SCREEN_WIDTH - 32.f fontSize:12.f];
//    self.headerView.height = 450.f - 14.f + height + 52.f + 30.f;
    self.headerView.height -= 50.f;
    
    long long highAmount = self.model.totalCredit.longLongValue;
    NSString *amountStr = [NSString stringWithFormat:@"%lld",highAmount];
    self.headerView.amountTF.placeholder = [NSString stringWithFormat:@"%@", formatAmount([NSDecimalNumber decimalNumberWithString:amountStr])];
//    self.headerView.titleLab.text = [NSString stringWithFormat:@"当前预估可借%@元",formatAmount([NSDecimalNumber decimalNumberWithString:amountStr])];
    self.headerView.titleLab.text = @"申请额度1万起，不支持1万以下";
    self.headerView.amountTF.text = amountStr;
    
    [self.headerView.borrowAllBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
        
        [self.view endEditing:YES];
        self.headerView.amountTF.text = [NSString stringWithFormat:@"%lld", highAmount];
        [self caculateRepaymentPlan];
    }];
    
    if (self.productsList.count == 0) {
        
        self.headerView.productLogo.hidden = YES;
        self.headerView.productLab.text = @"未匹配到资方";
        self.footerView.nextBtn.enabled = NO;
        self.footerView.backgroundColor = [MAIN_BLUE_COLOR colorWithAlphaComponent:.5f];
    }
    else {
     
        FPProducts *product = self.productsList.firstObject;
        [self.headerView.productLogo sd_setImageWithURL:[NSURL URLWithString:product.productLogo] placeholderImage:IMG(@"icon_home_placeholder")];
        self.headerView.productLab.text = product.productName;
    }
    
    // 查银行卡列表
    [self getBankCardList:NO];
}

#pragma mark - 获取服务器时间
- (void)getServiceDate {
    
    // 获取服务器当前时间
    [FPUserModel getServiceCurrenTimeSuccess:^(NSInteger code, NSString * _Nonnull message, NSString * _Nonnull currenTime) {
        
        if (code == 200) {
            
            self.dateFromService = [FPLoanDetailModel timeOfParam:currenTime];
        }
        
    } failure:^(NSError * _Nonnull error) {
    }];
}

#pragma mark - 获取协议
- (void)getProtocol {
    
    [FPProtocolModel getProtocolWithType:(FPProtocolTypeLoan) success:^(NSInteger code, NSString * _Nonnull message, NSArray *list) {
        [MBManager hideLoading];
        
        [self.protocolSource removeAllObjects];
        if (code == 200) {
            
            for (FPProtocolModel *model in list) {
                
                [self.protocolSource addObject:model];
            }
            
            NSMutableString *protocolStr = NSMutableString.string;
            
            for (FPProtocolModel *model in self.protocolSource) {
                
                [protocolStr appendFormat:@"%@",model.agreementName];
            }
            
            NSString *text = [NSString stringWithFormat:@"我已阅读并同意%@", protocolStr];
            
            NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
            
            for (NSInteger i = 0; i < self.protocolSource.count; i ++) {
                
                FPProtocolModel *model = self.protocolSource[i];
                
                NSRange range = [text rangeOfString:[NSString stringWithFormat:@"%@", model.agreementName]];
                [NSString stringToAttribute:attStr color:MAIN_BLUE_COLOR range:range];
                
                [self.footerView.privacyLab addLinkToURL:[NSURL URLWithString:model.address] withRange:range];
            }
            
            self.footerView.privacyLab.attributedText = attStr;
            self.footerView.privacyLab.delegate = self;
        }
        
    } failure:^(NSError * _Nonnull error) {
        [MBManager hideLoading];
    }];
}

#pragma mark - TTTAttributedLabelDelegate 处理协议点击
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
 
//    [MBManager showText:url.absoluteString];
    for (FPProtocolModel *model in self.protocolSource) {
        
        if ([url.absoluteString isEqualToString:model.address]) {
            
            FPMainWebController *vc = [[FPMainWebController alloc] init];
            
            FPProducts *product = self.productsList.firstObject;
            
            vc.cooperateName = product.cooperateName;
            vc.companyName = product.companyName;
            vc.model = model;
            vc.protocolType = FPProtocolTypeLoan;
            
            [self.navigationController pushViewController:vc animated:YES];
            return;
        }
    }
}

#pragma mark - 先查一下银行卡列表   selectLastCard: 最近添加了银行卡返回的回调 会显示最后一个,即最新一个
- (void)getBankCardList:(BOOL)selectLastCard {
    
    [MBManager showLoading];
    [FPBankCardModel getCardListSuccess:^(NSInteger code, NSString * _Nonnull message, NSArray * _Nonnull list) {
        [MBManager hideLoading];
        
        [self.bankCardSource removeAllObjects];
        
        // 刷新银行卡列表
        if (list.count == 0) {
            
            self.headerView.bankCardLab.text = @"请添加银行卡";
        }
        else {
            
            for (FPBankCardModel *model in list) {
                
                [self.bankCardSource addObject:model];
            }
            
            FPBankCardModel *model = list.firstObject;
            self.bankCardSelectIndex = 0;
            
            if (selectLastCard) {
                
                model = list.lastObject;
                self.bankCardSelectIndex = list.count - 1;
            }
            
            self.headerView.bankCardLab.text = [NSString stringWithFormat:@"%@(%@)", model.bankName , [model.bankCard substringFromIndex:(model.bankCard.length - 4)]];
            [self.headerView.bankCardImgView sd_setImageWithURL:[NSURL URLWithString:[FPUserModel.globalHeadURL stringByAppendingString:model.imagePath]] placeholderImage:IMG(@"icon_bank_card_default")];
            self.bankImgInfo = [FPUserModel.globalHeadURL stringByAppendingString:model.imagePath];
            self.bankCardInfo = [NSString stringWithFormat:@"%@(%@)", model.bankName , [model.bankCard substringFromIndex:(model.bankCard.length - 4)]];
            self.bankCardUserName = model.name;
            self.bankCardNumber = model.bankCard;
            self.affiliation = model.bankName;
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
    }];
}

- (void)selectAction {
    
    FeedBackGeneratorAction
    
    self.isSelect = !self.isSelect;
    
    if (self.isSelect) {
     
        self.footerView.selectImgView.image = SELECT_IMG_BLUE;
    }
    else {
     
        self.footerView.selectImgView.image = UNSELECT_IMG;
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    FPBaseTableViewCell *cell;
    
    if (cell == nil) {
        
        cell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPBaseTableViewCell.class) owner:nil options:nil].lastObject;
    }
    cell.backgroundColor = UIColor.clearColor;
    cell.userInteractionEnabled = NO;
    
    return cell;
}

#pragma mark - 借多少 textfield delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    NSInteger length = range.location + 1;
    
    if ([string isEqualToString:@""]) {
        
        if ([textField isEqual:self.headerView.amountTF]) {
            
            if (length <= 5) {
                
                self.headerView.noticeLab.hidden = NO;
            }
            else {
                
                self.headerView.noticeLab.hidden = YES;
            }
        }
        
        return YES;
    }
    
    // 数字 检查字符串是否为数字
    NSCharacterSet *nonDigitCharacterSet = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    if ([string rangeOfCharacterFromSet:nonDigitCharacterSet].location != NSNotFound) {
        
        return NO;  // 如果输入的字符不是数字，则不允许输入
    }
    
    if ([textField isEqual:self.headerView.amountTF]) {
        
        if (length < 5) {
            
            self.headerView.noticeLab.hidden = NO;
        }
        else {
            
            self.headerView.noticeLab.hidden = YES;
        }
        // 对输入的大小
        return textField.text.length < self.model.totalCredit.length;
    }
    
    return YES;
}	

- (void)textFieldDidEndEditing:(UITextField *)textField {
    
    if (textField.text.longLongValue >= self.model.totalCredit.longLongValue) {
        
        textField.text = self.model.totalCredit;
    }
    
    if (textField.text.length < 5) {
        
        self.headerView.noticeLab.hidden = NO;
    }
    else {
        
        self.headerView.noticeLab.hidden = YES;
    }
    
    [self caculateRepaymentPlan];
}

- (void)caculateRepaymentPlan {
    
    if (self.headerView.amountTF.text.length < 1) {
        
        return;
    }
    
    if (self.headerView.amountTF.text.length < 5) {
        
        return;
    }
    
    [FPRepayPlanModel getListWithAmount:self.headerView.amountTF.text instalments:[NSString stringWithFormat:@"%zd",self.termIndex] interestRate:self.rate sucess:^(NSInteger code, NSString * _Nonnull message, NSArray * _Nonnull list) {
        
        [self.repaymentSource removeAllObjects];
        // 首期........
        for (FPRepayPlanModel *model in list) {
            
            [self.repaymentSource addObject:model];
        }
        
        if (self.repaymentSource.count) {
            
            FPRepayPlanModel *model = self.repaymentSource.firstObject;
            NSArray *temp = [model.repaymentDate componentsSeparatedByString:@" "];
            NSString *timeStampStr = temp.firstObject;
            NSArray *finalTemp = [timeStampStr componentsSeparatedByString:@"-"];
            self.headerView.repayPlanLab.text = [NSString stringWithFormat:@"首期%@月%@日应还￥%.2f元", finalTemp[1] , finalTemp[2] , model.amount.doubleValue];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
    }];
}

#pragma mark - 借多久
- (void)periodSelectAction {
    
    [self.view endEditing:YES];
    
    // 创建弹窗，指定高度为 400
    CGFloat popupHeight = 254.f / 375.f * SCREEN_WIDTH;  // 根据需求调整高度
    FPCustomPopupView *popupView = [[FPCustomPopupView alloc] initWithHeight:popupHeight];
    
    self.headerPeriodMainView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPPeriodMainView.class) owner:nil options:nil].lastObject;
    [popupView.contentView addSubview:self.headerPeriodMainView];
    self.headerPeriodMainView.frame = CGRectMake(0.f, 0.f, SCREEN_WIDTH, popupHeight);
    self.headerPeriodMainView.index = self.termIndex;
    
    WeakSelf;
    self.headerPeriodMainView.transmitBlock = ^(NSUInteger index , NSString *termString) {
      
        weakSelf.termIndex = index;
        weakSelf.termString = termString;
        weakSelf.headerView.periodLab.text = termString;
        [popupView dismiss];
        [weakSelf caculateRepaymentPlan];
    };
    
    // 显示弹窗
    [popupView showInView:self.view];
}

#pragma mark - 还款计划
- (void)repaySelectAction {
    
    [self.view endEditing:YES];
    
    if (self.repaymentSource.count < 1) {
        
        FeedBackGeneratorAction
        [self.headerView.amountTF shake];
        return;
    }
    
    CGFloat popupHeight = 12.f + 44.f + 28.f + 100.f; // 其他控件的高度
    
    if (self.repaymentSource.count < 6) {
        
        popupHeight += self.repaymentSource.count * 60.f;
    }
    else {
        popupHeight += 6 * 60.f;
    }
    
    FPCustomPopupView *popupView = [[FPCustomPopupView alloc] initWithHeight:popupHeight];
    self.headerRepayPlanMainView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPRepayPlanMainView.class) owner:nil options:nil].lastObject;
    [popupView.contentView addSubview:self.headerRepayPlanMainView];
    
    self.headerRepayPlanMainView.term = self.termIndex;
    self.headerRepayPlanMainView.dataSource = self.repaymentSource;
    
    self.headerRepayPlanMainView.frame = CGRectMake(0.f, 0.f, SCREEN_WIDTH, popupHeight);
    
//    self.headerPeriodMainView.transmitBlock = ^(NSUInteger index) {
//      
//        NSLog(@"%zd",index);
//    };
    
    // 显示弹窗
    [popupView showInView:self.view];
}

#pragma mark - 选银行卡
- (void)bankInfoSelectAction {
    
    [self.view endEditing:YES];
    
    if (self.bankCardSource.count == 0) {
        
        [self addNewCardAction];
        return;
    }
    
    CGFloat popupHeight = 70.f + 58.f; // 其他控件的高度
    
    if (self.bankCardSource.count < 6) {
        
        popupHeight += 68.f * self.bankCardSource.count;
    }
    else {
        
        popupHeight += 68.f * 6;
    }
    
    FPCustomPopupView *popupView = [[FPCustomPopupView alloc] initWithHeight:popupHeight];
    self.bankCardInfoMainView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPBankCardInfoMainView.class) owner:nil options:nil].lastObject;
    [popupView.contentView addSubview:self.bankCardInfoMainView];
    popupView.tag = 9000;
    
    self.bankCardInfoMainView.dataSource = self.bankCardSource;
    
    self.bankCardInfoMainView.frame = CGRectMake(0.f, 0.f, SCREEN_WIDTH, popupHeight);
    
//    self.headerPeriodMainView.transmitBlock = ^(NSUInteger index) {
//
//        NSLog(@"%zd",index);
//    };
    
    // 显示弹窗
    [popupView showInView:self.view];
    
    WeakSelf;
    self.bankCardInfoMainView.selectBankCardBlock = ^(NSInteger index) {
        
        FPBankCardModel *model = weakSelf.bankCardSource[index];
        weakSelf.headerView.bankCardLab.text = [NSString stringWithFormat:@"%@(%@)", model.bankName , [model.bankCard substringFromIndex:(model.bankCard.length - 4)]];
        [weakSelf.headerView.bankCardImgView sd_setImageWithURL:[NSURL URLWithString:[FPUserModel.globalHeadURL stringByAppendingString:model.imagePath]] placeholderImage:IMG(@"icon_bank_card_default")];
        weakSelf.bankCardSelectIndex = index;
        
        weakSelf.bankImgInfo = [FPUserModel.globalHeadURL stringByAppendingString:model.imagePath];
        weakSelf.bankCardInfo = [NSString stringWithFormat:@"%@(%@)", model.bankName , [model.bankCard substringFromIndex:(model.bankCard.length - 4)]];
        weakSelf.bankCardUserName = model.name;
        weakSelf.bankCardNumber = model.bankCard;
        weakSelf.affiliation = model.bankName;
//        [weakSelf showText:[NSString stringWithFormat:@"选中银行卡第~%zd",index]];
        [popupView dismiss];
    };
    
    [self.bankCardInfoMainView.bottomView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addNewCardAction)]];
}

#pragma mark - 借款用途
- (void)purposeSelectAction {
    
    [self.view endEditing:YES];
    HJCActionSheet *sheet = [[HJCActionSheet alloc] initWithDelegate:self CancelTitle:@"取消" OtherTitlesArray:self.usageArray];
    [sheet show];
}

#pragma mark - 添加银行卡
- (void)addNewCardAction {
    
    FPCustomPopupView *view = (FPCustomPopupView *)[self.view viewWithTag:9000];
    [view dismiss];
    
    FPAddNewBankCardController *vc = [[FPAddNewBankCardController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    
    // 刷新银行卡列表
    WeakSelf;
    vc.bankCardBlock = ^() {
        
        [weakSelf getBankCardList:YES];
//        weakSelf.headerView.bankCardLab.text = [NSString stringWithFormat:@"%@(%@)", model.affiliation , [model.cardNumber substringFromIndex:(model.cardNumber.length - 4)]];
//        self.headerView.bankCardImgView.image = IMG(model.logo);
    };
}

- (void)actionSheet:(HJCActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    
//    [self showText:[NSString stringWithFormat:@"tap index %zd",buttonIndex]];
    self.usageIndex = buttonIndex - 1;
    self.headerView.purposeLab.text = self.usageArray[self.usageIndex];
}

- (void)submitAction {
    
    if (self.headerView.amountTF.text.length < 1) {
        
        FeedBackGeneratorAction
        [self.headerView.amountTF shake];
        return;
    }
    
    if (self.headerView.amountTF.text.length < 5) {
        
        FeedBackGeneratorAction
        self.headerView.noticeLab.hidden = NO;
        [self.headerView.amountTF shake];
        return;
    }
    
    if (self.bankCardSelectIndex == -1) {
        
        FeedBackGeneratorAction
        [self.headerView.bankInfoView shake];
        return;
    }
    
    if (!self.isSelect) {
        
        [FPBaseProtocolView showWithText:self.protocolSource onAction:^(NSUInteger index) {
            
            if (index == 1001) {
                
                // 拒绝
            }
            else {
                
                [self selectAction];
            }
            
        } protocolDidSelectAction:^(FPProtocolModel * _Nonnull model) {
            
//                NSLog(@"%@",model.agreementName);
            FPMainWebController *vc = [[FPMainWebController alloc] init];
            vc.model = model;
            vc.protocolType = FPProtocolTypeLogin;
            [self.navigationController pushViewController:vc animated:YES];
        }];
        
//        FeedBackGeneratorAction
//        [self.footerView.selectImgView shake];
//        [self.footerView.privacyLab shake];
        return;
    }
    
    self.headerView.noticeLab.hidden = YES;
    
    // 埋点
    [FPRecordPointModel recordPointWithType:@"3" success:^(NSInteger code, NSString * _Nonnull message) {
    } failure:^(NSError * _Nonnull error) {
    }];
    
    
    
    FPProducts *product = self.productsList.firstObject;
    
    [self applyProduct:product];
    
    
    
//    NSMutableDictionary *param = APIClient.creatAPIDictionary;
//    
//    FPBankCardModel *bankCardModel = self.bankCardSource[self.bankCardSelectIndex];
//    
//    [param setObject:self.headerView.amountTF.text forKey:@"amount"];
//    [param setObject:self.rate forKey:@"interestRate"];
//    [param setObject:@(self.termIndex) forKey:@"lengthOfMaturity"];
//    [param setObject:@(self.usageIndex) forKey:@"loanPurpose"];
//    [param setObject:bankCardModel.ID forKey:@"userBankCardId"]; // 银行卡ID
//    
//    
//    FPLoanModel *tempModel = [[FPLoanModel alloc] init];
//    
//    tempModel.amount = self.headerView.amountTF.text;
//    tempModel.rate = self.rate;
//    tempModel.limit = [NSString stringWithFormat:@"%zd期" , (self.termIndex + 1) * 3];
//    tempModel.repayWay = @"等额本息-分期还款";
//    
//    NSString *phone = [FPUserModel AES256Encrypt:FPUserInfoModel.sharedUserInfo.phone];
//    tempModel.phone = phone;
//    
//    tempModel.residentialDetailsAddress = FPUserInfoModel.sharedUserInfo.residentialDetailsAddress;
//    tempModel.userName = FPUserInfoModel.sharedUserInfo.idcardName;
//    
//    NSString *cardNumber = [FPUserModel AES256Encrypt:FPUserInfoModel.sharedUserInfo.idcardNumber];
//    tempModel.idNumber = cardNumber;
//    
//    tempModel.date = self.dateFromService;
//    tempModel.repayDay = @"每月10日";
//    
//    tempModel.bankCardUserName = FPUserInfoModel.sharedUserInfo.idcardName;
//    
//    NSString *bankCardNumber = [FPUserModel AES256Encrypt:self.bankCardNumber];
//    tempModel.bankCardNumber = bankCardNumber;
//    tempModel.bankCardInfo = self.affiliation;
//    tempModel.loanPurpose = self.usageArray[self.usageIndex];
//    tempModel.capitalLetters = [NSString toCapitalLetters:tempModel.amount];
//    
//    NSDate *date = [NSDate date];
//    // 获取自1970年1月1日起的秒数
//    NSTimeInterval timeInterval = [date timeIntervalSince1970];
//        
//    // 转换为毫秒级时间戳（乘以1000）
//    long long timestamp = (long long)(timeInterval * 1000);
//    self.keyContractWithTimestamp = [NSString stringWithFormat:@"loanContract%lld",timestamp];
//    
//    [MBManager showLoading];
//    [FPLoanModel saveLoanContractInfoWithParam:tempModel timeStamp:timestamp success:^(NSInteger code, NSString * _Nonnull message) {
//        [MBManager hideLoading];
//        
//        if (code == 200) {
//            
//            FPConfirmLoanContractController *vc = [[FPConfirmLoanContractController alloc] init];
//            
//            vc.param = param;
//            vc.bankCardInfo = self.bankCardInfo;
//            vc.bankCardImgInfo = self.bankImgInfo;
//            vc.amountInfo = self.headerView.amountTF.text;
//            vc.protocolSource = self.protocolSource;
//            vc.keyContractWithTimestamp = self.keyContractWithTimestamp;
//            
//            [self.navigationController pushViewController:vc animated:YES];
//        }
//        else {
//            
//            [self showText:message];
//        }
//        
//    } failure:^(NSError * _Nonnull error) {
//        [self showError:error];
//    }];
}


- (void)applyProduct:(FPProducts *)product {
    
    NSString *num = [FPUserModel AES256Encrypt:FPUserInfoModel.sharedUserInfo.phone];
    
    NSMutableDictionary *param = APIClient.creatAPIDictionary;
    
    [param setValue:product.advertId                forKey:@"advertId"];
    [param setValue:product.companyId               forKey:@"companyId"];
    [param setValue:self.infoModel.customerId       forKey:@"customerId"];
    [param setValue:self.infoModel.requestId        forKey:@"requestId"];
    [param setValue:num                             forKey:@"customerPhone"];
    [param setValue:product.price                   forKey:@"price"];
    [param setValue:product.productName             forKey:@"productName"];
    [param setValue:product.productLogo             forKey:@"productLogo"];
    
    [param setValue:product.cooperateName           forKey:@"cooperateName"];
    [param setValue:product.companyName             forKey:@"companyName"];
    
    [param setValue:self.headerView.amountTF.text   forKey:@"amount"];
    
    [MBManager showLoading];
    [FPRepayPlanModel applyLoanWithParam:param success:^(NSInteger code, NSString * _Nonnull message , BOOL isSuccess) {
        [MBManager hideLoading];
        
        if (code == 200) {
            
            if (isSuccess) {
                
                FPRecommonProductController *vc = [[FPRecommonProductController alloc] init];
                
                vc.infoModel = self.infoModel;
                
                if (self.index + 1 == self.productsList.count) {
                    
    //                vc.productList = self.productsList;
                }
                else {
                    
                    vc.productList = self.productsList;
                }
                
                [self signProtocolWithParams:self.protocolSource];
                [self.navigationController pushViewController:vc animated:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:LoanApplySuccessNotification object:nil];
            }
            else {
              
                self.index ++;
                
                if (self.productsList.count <= self.index + 1) {
                    
                    [self applyProduct:[self.productsList objectAtIndex:self.index]];
                }
                else {
                    
                    // 全部都申请失败了
                    FPRecommonProductController *vc = [[FPRecommonProductController alloc] init];
                    [self signProtocolWithParams:self.protocolSource];
                    vc.infoModel = self.infoModel;
                    [self.navigationController pushViewController:vc animated:YES];
                }
            }
        }
        else {
            
            [self showText:message];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
    }];
    
}


@end
